﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FPP.Models;
using FPP.Custom;
using System.Data.Objects;
using System.Web.Security;
using System.IO;

namespace FPP.Controllers
{
    public class BaseController : Controller
    {

        public fppEntities _context;
        public CustomMembershipProvider _provider;

        public fppEntities context
        {
            get
            {
                _context = new fppEntities(DataAccess.ffpCString);
                return _context;
            }
        }
        public CustomMembershipProvider provider
        {
            get { 
                if (_provider == null) _provider = (CustomMembershipProvider)Membership.Provider;
                return _provider; 
            }
        }

        /// <summary>
        /// Will Return A User Object Based on the Login Token
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public User GetUserFromLoginToken(string token)
        {
            if (string.IsNullOrEmpty(token)) return new User();

            User _user;

            fppEntities quickContext = new fppEntities(DataAccess.ffpCString);
            using (quickContext)
            {
                _user = quickContext.Users.FirstOrDefault(q => q.LoginToken == token);
                if (_user == null) return new User();

                if (_user.LoginExp < DateTime.Now) return new User { FirstName = "Login Expired", LastName = "Expired", };

                _user.LoginExp = DateTime.Now.AddDays(1);

                quickContext.SaveChanges(SaveOptions.None);
            }

            return _user;

        }

        protected string RenderPartialViewToString()
        {
            return RenderPartialViewToString(null, null);
        }

        protected string RenderPartialViewToString(string viewName)
        {
            return RenderPartialViewToString(viewName, null);
        }

        protected string RenderPartialViewToString(object model)
        {
            return RenderPartialViewToString(null, model);
        }

        protected string RenderPartialViewToString(string viewName, object model)
        {
            if (string.IsNullOrEmpty(viewName))
                viewName = ControllerContext.RouteData.GetRequiredString("action");

            ViewData.Model = model;

            using (StringWriter sw = new StringWriter())
            {
                ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
                ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
                viewResult.View.Render(viewContext, sw);

                return sw.GetStringBuilder().ToString();
            }
        }

    }
}
